package dyy.zc.note.ui.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.bmob.v3.datatype.BmobFile;
import dyy.zc.note.R;
import dyy.zc.note.application.MyApplication;
import dyy.zc.note.base.BaseActivity;
import dyy.zc.note.bean.NoteInfo;
import dyy.zc.note.listener.OnItemClickListener;
import dyy.zc.note.ui.adapter.ImgAdapter;
import dyy.zc.note.utils.AppManager;
import dyy.zc.note.utils.BmobUtils;
import dyy.zc.note.utils.DBControl;
import dyy.zc.note.utils.ImageUploadUtil;
import dyy.zc.note.utils.ImageUtil;
import dyy.zc.note.utils.StringUtils;
import dyy.zc.note.utils.ToastUtils;
import dyy.zc.note.views.ActionSheet;
import dyy.zc.note.views.MyAlertDialog;

public class WriteActivity extends BaseActivity implements View.OnClickListener ,ActionSheet.OnSheetItemClickListener{

    private DBControl dbControl;
    private EditText content,titleContent;
    private SimpleDateFormat sdf;
    private ImageView photo;
    private TextView type,right;
    private RelativeLayout save;
    private RecyclerView recyclerView;
    private ImgAdapter adapter;
    private List<BmobFile> ImgList = new ArrayList<>();
    private BmobUtils bmobUtils;
    private List<String> typeList = new ArrayList<>();
    private NoteInfo noteInfo;

    private String[] items = {"拍照", "我的相册"};
    // 头像文件、上传头像的名称、本地图片uri
    private File imageFile;
    private Uri imageUri; // 图片路径
    //拍照、从相册选择、照片保存成功
    private final int TAKE_PHOTO = 1, CHOOSE_PHOTO = 2, SAVE_IMAGE_SUCCESS = 3;
    private final int SAVE_SUCCESS = 123;
    private final int UPDATE_SUCCESS = 234;
    private boolean hasImg = false;
    private boolean check = false;
    @Override
    protected void findViewByIDS() {
        content = findViewsById(R.id.content);
        titleContent = findViewsById(R.id.titleName);
        photo = findViewsById(R.id.photo);
        save = findViewsById(R.id.top_rl_right);
        right = findViewsById(R.id.top_tv_right);
        type = findViewsById(R.id.type);
        recyclerView = findViewsById(R.id.recyclerView);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_write);
        initData();
        bind();
    }

    private void bind() {
        save.setOnClickListener(this);
        photo.setOnClickListener(this);
        type.setOnClickListener(this);
        adapter = new ImgAdapter(this,ImgList);
        recyclerView.setLayoutManager(new GridLayoutManager(this,2));
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                deleteDialog(position);
            }
        });
    }

    /**
     * 删除图片
     * @param position
     */
    private void deleteDialog(final int position) {

            MyAlertDialog logDialog = new MyAlertDialog(this);
            logDialog.builder()
                    .setTitle("删除提示")
                    .setMsg("是否要删除？")
                    .setNegativeButton("取消", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    })
                    .setPositiveButton("确定", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                        ImgList.remove(position);
                            adapter.setList(ImgList);
                            adapter.notifyDataSetChanged();
                        }
                    })
                    .show();

    }

    private void initData() {
        noteInfo = new NoteInfo();
        Intent intent = getIntent();
        loginuser = MyApplication.getInstance().readLoginUser();
        if (intent.getIntExtra("has",0)==1){//表示从点击照相进入的
            hasImg = true;
            ImgList.add((BmobFile) getIntent().getSerializableExtra("file"));
        }
        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dbControl = new DBControl(this);
        bmobUtils = new BmobUtils(this);


        if (loginuser == null){//未登录
            typeList.add("我的日记");
        }else {
            if (intent.getIntExtra("hasClass",0)==1){
                List<String> nameList = (List<String>) intent.getSerializableExtra("classify");
                typeList.add("我的日记");
                typeList.addAll(nameList);
            }
        }

        if (intent.getIntExtra("check",0)==1){
            check = true;
            noteInfo = (NoteInfo) intent.getSerializableExtra("note");
            titleContent.setText(noteInfo.getTitle());
            content.setText(noteInfo.getContent());
            if (noteInfo.getType().equals("-1")){
                type.setText("我的日记");
            }else {
                type.setText(noteInfo.getType());
            }
            if (loginuser != null){
                if (noteInfo.getImg() != null){
                    ImgList = noteInfo.getImg();
                }
            }

        }
//        typeList.add("新建分组");
    }

//    @Override
//    public void backClick(View view) {
//        dbControl.insert(content.getText().toString(),
//                titleContent.getText().toString(),1,"",sdf.format(new Date()));
//        finish();
//    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.photo://加照片
                if (loginuser!=null){
                    showActionSheetDialog(items);
                }else {
                    ToastUtils.shortToast(WriteActivity.this,"登录之后才能上传照片哟~~");
                }
                break;
            case R.id.top_rl_right://保存
                if (check){//更新日记
                    updateNote();
                }else {//保存新日记
                    saveNote();
                }
                break;
            case R.id.type://选择类型
                initPopUpWindow(typeList, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (typeList.get(datePicker.getCurrentItemPosition()).equals("新建分组")){
                            mPopupWindow.dismiss();
                            ToastUtils.shortToast(WriteActivity.this,"登录之后才能新建分组哟~~");
                        }else {
                            type.setText(typeList.get(datePicker.getCurrentItemPosition()));
                            //设置日记类别
                            noteInfo.setType(typeList.get(datePicker.getCurrentItemPosition()));
                        }
                        mPopupWindow.dismiss();
                    }
                });
                break;
        }
    }

    /**
     * 保存新日记
     */
    private void saveNote() {
        if (type.getText().toString().equals("选择类型")){
            ToastUtils.shortToast(WriteActivity.this,"请选择类型哟~~");
        }else {
            if (StringUtils.isEmpty(content.getText().toString())||
                    StringUtils.isEmpty(titleContent.getText().toString())){
                ToastUtils.shortToast(WriteActivity.this,"标题和内容不能为空~~");
            }else {
                dialog = ProgressDialog.show(WriteActivity.this,null,"正在保存......");
                if (loginuser == null){//未登录。保存本地数据库
                    String imageAdress = "";
                    //String content,String title,int type,String img,String timeStr
                    dbControl.insert(content.getText().toString(),
                            titleContent.getText().toString(),-1,sdf.format(new Date()));
                    dialog.dismiss();
                    finish();
                }else {//已登录上传服务器
                    noteInfo.setTimeStr("");
                    noteInfo.setId(loginuser.getId());
                    noteInfo.setImg(ImgList);
                    noteInfo.setTitle(titleContent.getText().toString());
                    noteInfo.setContent(content.getText().toString());
                    bmobUtils.saveNoteInfo(noteInfo,SAVE_SUCCESS,handler);
                }

            }
        }
    }

    /**
     * 更新日记
     */
    private void updateNote() {
        if (StringUtils.isEmpty(content.getText().toString())||
                StringUtils.isEmpty(titleContent.getText().toString())){
            ToastUtils.shortToast(WriteActivity.this,"标题和内容不能为空~~");
        }else {
            dialog = ProgressDialog.show(WriteActivity.this,null,"正在保存......");
            if (loginuser == null){//未登录。保存本地数据库
                String imageAdress = "";
                //String content,String title,int type,String img,String timeStr
                dbControl.update(noteInfo.getId(),content.getText().toString(),
                        titleContent.getText().toString(),-1,sdf.format(new Date()));
                dialog.dismiss();
                finish();
            }else {//已登录上传服务器
                noteInfo.setTimeStr("");
                noteInfo.setId(loginuser.getId());
                noteInfo.setImg(ImgList);
                noteInfo.setTitle(titleContent.getText().toString());
                noteInfo.setContent(content.getText().toString());
                bmobUtils.updateNoteInfo(noteInfo,SAVE_SUCCESS,handler);
            }

        }
    }

    //头像选择对话框
    private void showActionSheetDialog(String[] items) {
        ActionSheet actionSheet = new ActionSheet(this)
                .builder()
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        for (int i = 0; i < items.length; i++) {
            actionSheet.addSheetItem(items[i], ActionSheet.SheetItemColor.Blue, WriteActivity.this);
        }
        actionSheet.show();

    }

    @Override
    public void onClick(int which) {
        switch (which) {
            case TAKE_PHOTO:
                //拍照
                imageFile = ImageUploadUtil.createImageFile(ImageUploadUtil.CAMERA_SAVEDIR2, ImageUploadUtil.createImageName());
                startActivityForResult(ImageUploadUtil.intentImageCapture(imageFile), ImageUploadUtil.TAKE_PHOTO);
                break;
            case CHOOSE_PHOTO:
                //从相册选择
                startActivityForResult(ImageUtil.intentChooseImg(),
                        CHOOSE_PHOTO);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == 0) {
                    return;
                }
                //拍照
                ImageUtil.paizhaocreateImagefile(this, imageFile);
                if (imageFile == null) {
                    ToastUtils.shortToast(this, "图片太大无法上传");
                    return;
                }
                doSendThread();//上传图片
                break;
            case CHOOSE_PHOTO:
                //相册
                if (resultCode == 0) return;
                imageUri = data.getData();
                imageFile = MyApplication.getInstance().createimagefile(imageUri, getVmWidth(), getVmHeight());
                if (imageFile == null) {
                    ToastUtils.shortToast(this, "imageFile为空2");
                    return;
                }
                doSendThread();//上传图片
                break;
        }

    }
    /**
     * 上传头像
     */
    private void doSendThread() {
        dialog = ProgressDialog.show(this, null, "正在上传图片...");
//        Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getPath());
//        head.setImageBitmap(bitmap);
        BmobFile bmobFile = new BmobFile(imageFile);
        bmobUtils.upLoadImage(ImgList,bmobFile,SAVE_IMAGE_SUCCESS, handler);
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case SAVE_IMAGE_SUCCESS:
                    hasImg = true;
                    adapter.setList(ImgList);
                    adapter.notifyDataSetChanged();
                    dialog.dismiss();
                    break;
                case SAVE_SUCCESS:
                    dialog.dismiss();
                    finish();
                    break;
            }
        }
    };
}
